package com.orderVideo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orderVideo.common.Result;
import com.orderVideo.dto.OrderQueryDTO;
import com.orderVideo.entity.Order;
import com.orderVideo.entity.User;
import com.orderVideo.entity.Video;
import com.orderVideo.enums.OrderQueryType;
import com.orderVideo.mapper.OrderMapper;
import com.orderVideo.mapper.UserMapper;
import com.orderVideo.service.OrderService;
import com.orderVideo.utils.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/order")
//@RequestMapping("/api2/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户订单列表（分页）
     *
     * @param queryDTO 查询参数DTO，包含查询类型、页码、每页数量
     * @return 分页订单列表
     *
     * 请求示例：
     * POST /api/order/user/list
     * {
     *   "queryType": 1,   // 1=今天，2=本周，3=本月
     *   "pageNum": 1,     // 页码
     *   "pageSize": 10    // 每页数量
     * }
     */
    @PostMapping("/user/list")
    public Result<IPage<Order>> getUserOrders(@RequestBody OrderQueryDTO queryDTO) {
        try {
            // 参数验证
            if (queryDTO == null) {
                return Result.error("查询参数不能为空");
            }
            // 获取查询类型
            OrderQueryType queryType = OrderQueryType.getByCode(queryDTO.getQueryType());
            if (queryDTO.getQueryType() != null && queryType == null) {
                return Result.error("无效的查询类型");
            }
            // 查询订单
            IPage<Order> orders = orderService.queryOrdersPage(LoginUser.getUserId(),
                    queryDTO.getPageNum(), queryDTO.getPageSize(),  queryType);
            return Result.success(orders);
        } catch (Exception e) {
            log.error("查询订单失败", e);
            return Result.error("查询订单失败：" + e.getMessage());
        }
    }

    /**
     * 管理员创建订单
     *
     * @param requestOrder 订单信息，包含用户ID、订单金额、订单状态等
     * @return 创建的订单信息
     *
     * 请求示例：
     * POST /api/order/admin/create
     * {
     *   "userId": 1,
     *   "orderMoney": 100.00,
     *   "orderStatus": 1,   // 1=已完成
     *   "orderInfo": "订单描述"
     * }
     */
    @PostMapping("/admin/create")
    public Result<Order> createOrder(@RequestBody Order requestOrder) {
        try {
            Order order = orderService.createOrder(requestOrder);
            return Result.success(order);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/admin/update")
    public Result<Void> updateOrder(@RequestBody Order requestOrder) {
        try {
            orderMapper.updateById(requestOrder);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 管理员更新订单状态
     *
     * @param orderId 订单ID
     * @param status 新状态值（0=未完成，1=已完成）
     * @return 更新结果
     *
     * 请求示例：
     * PUT /api/order/admin/status/1?status=1
     */
    @PutMapping("/admin/status/{orderId}")
    public Result<Boolean> updateOrderStatus(@PathVariable Long orderId, @RequestParam Integer status) {
        try {
            boolean success = orderService.updateOrderStatus(orderId, status);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 管理员查询所有订单（分页）
     *
     * @param queryDTO 查询参数DTO，包含查询类型、页码、每页数量
     * @return 分页订单列表
     *
     * 请求示例：
     * POST /api/order/admin/list
     * {
     *   "queryType": 1,   // 1=今天，2=本周，3=本月
     *   "pageNum": 1,     // 页码
     *   "pageSize": 10    // 每页数量
     * }
     */
    @PostMapping("/admin/list")
    public Result<IPage<Order>> getAdminOrders(@RequestBody OrderQueryDTO queryDTO) {
        try {
            IPage<Order> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());
            // 查询订单
            IPage<Order> orders = orderMapper.selectPage(page, null);
            List<Order> records = orders.getRecords();
            if (records != null && !records.isEmpty()) {
                for (Order order : records) {
                    User user = userMapper.selectById(order.getUserId());
                    if (user != null) {
                        order.setUserName(user.getUsername());
                        order.setNickName(user.getNickName());
                    }
                }
            }
            orders.setRecords(records);
            return Result.success(orders);
        } catch (Exception e) {
            log.error("查询订单失败", e);
            return Result.error("查询订单失败：" + e.getMessage());
        }
    }

    /**
     * 管理员删除订单
     *
     * @param orderId 订单ID
     * @return 删除结果
     *
     * 请求示例：
     * DELETE /api/order/admin/1
     */
    @DeleteMapping("/admin/{orderId}")
    public Result<Boolean> deleteOrder(@PathVariable Long orderId) {
        try {
            boolean success = orderService.deleteOrder(orderId);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
} 